package com.kelvin.oocl.testTransaction.service.impl;

import com.kelvin.oocl.testTransaction.tool.DBUtils;
import com.kelvin.oocl.testTransaction.dao.CustomerDao;
import com.kelvin.oocl.testTransaction.dao.EmployeeDao;
import com.kelvin.oocl.testTransaction.dao.impl.CustomerDaoImpl;
import com.kelvin.oocl.testTransaction.dao.impl.EmployeeDaoImpl;
import com.kelvin.oocl.testTransaction.exception.DBOperationException;
import com.kelvin.oocl.testTransaction.model.Customer;
import com.kelvin.oocl.testTransaction.model.Employee;
import com.kelvin.oocl.testTransaction.service.UserService;

import java.sql.Connection;

public class UserServiceImpl implements UserService {
	CustomerDao dao1 = new CustomerDaoImpl();
	EmployeeDao dao2 = new EmployeeDaoImpl();

	@Override
	public int save(Customer customer, Employee emp) {
		dao1.save(customer);
		dao2.save(emp);
		return 2;
	}

	@Override
	public int saveWithNoProxy(Customer customer, Employee emp) throws Exception {
		//开启事务
		Connection conn = null;
		try {
			System.out.println("start transaction");
			conn = DBUtils.getConnection();
			conn.setAutoCommit(false);
			dao1.save(customer);
			dao2.save(emp);
			conn.commit();
			System.out.println("commit transaction");
			return 1;
		} catch (DBOperationException ex){
			System.out.println("rollback transaction");
			conn.rollback();
			ex.printStackTrace();
			throw new DBOperationException("service operation failed.");
		}
	}

}
